package com.whh.tq;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.whh.tq.bean.Favorite;
import com.whh.tq.bean.QueryResultInfo;
import com.whh.tq.common.AndroidHelper;
import com.whh.tq.common.AsyncLoader;
import com.whh.tq.common.AsyncLoader.Callback;
import com.whh.tq.common.AsyncLoader.Execute;
import com.whh.tq.common.HttpHelper;
import com.whh.tq.common.ReqParamHelper;
import com.whh.tq.common.ResContentHelper;
import com.whh.tq.service.FavoriteService;
import com.whh.tq.service.FavoriteServiceImpl;

public class StationResultActivity extends Activity {
	private Resources resources; 
	
	private List<QueryResultInfo> queryResultList = new ArrayList<QueryResultInfo>();
	private TimetableResultAdapter adapter;
	private ListView listStationResult;
	private TextView textStationResultTitle;
	private TextView textStationCount;
	private ProgressBar progressLoading;
	private FavoriteService favoriteService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_station_result);
		init();
	}

	private void init() {
		resources = getApplicationContext().getResources();
		progressLoading = (ProgressBar)findViewById(R.id.progress_loading);
		textStationResultTitle = (TextView)findViewById(R.id.text_station_result_title);
		textStationCount = (TextView)findViewById(R.id.text_station_count);
		listStationResult = (ListView)findViewById(R.id.list_station_result);
		favoriteService = new FavoriteServiceImpl(getApplicationContext());
		registerForContextMenu(listStationResult);
		
		Bundle bundle = this.getIntent().getExtras();
		final String date = bundle.getString("date");
		String[] strArray=date.split("-");
		final String year = strArray[0];
		final String month = strArray[1];
		final String day = strArray[2];
		final String station = bundle.getString("station");
		textStationResultTitle.setText(station+"  ["+date+"]");
		textStationCount.setText(resources.getString(R.string.text_loading));
		
		AsyncLoader.execute(new Execute() {
			@Override
			public Object execute() {
				String res = HttpHelper.getHtml(ReqParamHelper.getStationGetDataUrl(year, month, day, station),ReqParamHelper.REFERER_STATION);
				//判断是否有验证码错误等问题
				if(res == null){
					return resources.getString(R.string.text_query_error);
				}else if(res.indexOf(resources.getString(R.string.text_query_error))>0){
					return resources.getString(R.string.text_query_error);
				}
				queryResultList=ResContentHelper.parseStationResContent(res);
				return null;
			}
		}, new Callback() {
			@Override
			public void callback(Object obj) {	
				if(null != obj){
					AndroidHelper.showToast(StationResultActivity.this,obj.toString());
				}else {
					if (null == adapter) {
						adapter = new TimetableResultAdapter();
						listStationResult.setAdapter(adapter);
					} else {
						adapter.notifyDataSetChanged();
					}					
				}
				textStationCount.setText(resources.getString(R.string.text_total_train_count).replace("XX", queryResultList.size()+""));			
				progressLoading.setVisibility(View.GONE);
			}
		});
	}
	
	/**
	 * 长按listview中的item弹出菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		//获取当前长按的下标
	    int i = ((AdapterContextMenuInfo)menuInfo).position; 
		String trainCode = queryResultList.get(i).getTrainCode();
		menu.setHeaderTitle(trainCode);
		menu.add(0, 1, 0, resources.getString(R.string.text_menu_favorite));
	}
	
	/**
	 * 弹出菜单点击
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		//menuInfo中包含很多属性，其中id就是ListView的Item的id，targetView则是ListView中Item的view
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 
		// int itemId = Integer.valueOf(menuInfo.id+"");
		// View v = listTrainCodeResult.getChildAt(itemId);
		View v = menuInfo.targetView;
		TextView textTrainCode = (TextView)v.findViewById(R.id.text_trainCode);
		String trainCode = textTrainCode.getText().toString();
		if(!favoriteService.isExits(trainCode, null)){
			Favorite fav = new Favorite();
			fav.setTrainCode(trainCode);
			favoriteService.save(fav);
		}
		AndroidHelper.showToast(getApplicationContext(),resources.getString(R.string.text_menu_favorite)+":"+trainCode);
		return true;
		//return super.onContextItemSelected(item);
	}

	private class TimetableResultAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return queryResultList.size();
		}

		@Override
		public Object getItem(int position) {
			return queryResultList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_station_result, null);
			QueryResultInfo result = queryResultList.get(position);
			TextView textTrainCode = (TextView) view.findViewById(R.id.text_trainCode);
			TextView textStartStationEndStation = (TextView) view.findViewById(R.id.text_start_station_end_station);
			TextView textStartTimeEndTime = (TextView) view.findViewById(R.id.text_start_time_end_time);
			TextView textStation = (TextView) view.findViewById(R.id.text_station);
			TextView textUsedTime = (TextView) view.findViewById(R.id.text_used_time);
			textTrainCode.setText(result.getTrainCode());
			textStartStationEndStation.setText("[" + result.getStartStation() + "-"+ result.getEndStation() + "]");
			textStartTimeEndTime.setText("[" + result.getStartTime() + "-"+ result.getEndTime() + "]");
			textStation.setText(result.getStation()+" ["+result.getToTime()+"-"+result.getFromTime()+"]");
			textUsedTime.setText(result.getUsedTime());
			return view;
		}

	}
}
